<template lang="pug">
  .CreateAccountModal
    Modal(
      v-model="isShowCreateModal"
      :title="createModalTitle"
      class-name="vertical-center-modal"
      width="700"
    )
      Form.ivu-row.has-rules-item2.ivu-form-basic(ref="formData" :model="formData" :rules="rules" :label-width="150")
        FormItem.form-item.ivu-col(v-for="(item, index) of setFormItem" :label="item.label" :key="index" :class="item.style" :prop="item.prop" v-show="item.isShow")
          template(v-if="item.type === 'input'")
            Input(v-if="item.fn" v-model="formData[item.model]" :placeholder="item.placeholder" :disabled="item.isDisabled" clearable @on-blur="(event, type) => listenCall(item.fn, item.model, event)")
            Input(v-else v-model="formData[item.model]" :placeholder="item.placeholder" :disabled="item.isDisabled" clearable :type="item.inputType ? item.inputType: 'text'")
          template(v-if="item.type === 'select'")
            Select(v-if="item.model == 'insuranceTypes'" v-model="formData[item.model]" :placeholder="item.placeholder" clearable filterable multiple :max-tag-count="1" :disabled="item.isDisabled" @on-change="(event, type) => listenCall(item.fn, item.model, event)")
              Option(v-for="(c_item, c_index) of arrListDown[item.options]" :key="c_index" :value="c_item.key") {{c_item.value}}
            Select(v-else-if="item.fn" v-model="formData[item.model]" :placeholder="item.placeholder" clearable filterable :disabled="item.isDisabled" @on-change="(event, type) => listenCall(item.fn, item.model, event)")
              Option(v-for="(c_item, c_index) of arrListDown[item.options]" :key="c_index" :value="c_item.value") {{c_item.label}}
            Select(v-else v-model="formData[item.model]" :placeholder="item.placeholder" clearable filterable :disabled="item.isDisabled")
              Option(v-for="(c_item, c_index) of arrListDown[item.options]" :key="c_index" :value="c_item.value") {{c_item.label}}
          template(v-if="item.type === 'datePicker'")
            DatePicker.w-100(v-model="formData[item.model]" :placeholder="item.placeholder" :type="item.mode ? item.mode : 'date'" :disabled="item.isDisabled" @on-change="(event, type) => listenCall(item.fn, item.model, event)")
          template(v-if="item.type === 'switch'")
            i-switch(v-model="formData[item.model]")
      
      .clearfix(slot="footer")
        Button(type="text" @click="cancel") 取消
        Button(v-if="modalKey != 'lookModal'" type="primary" @click="handleSubmit" :loading="!isCanSubmit") 保存
</template>

<script>
import { Common } from '@/utils/common.js'
import _cloneDeep from 'clone-deep'
import { FinanceApi } from '@/api/Finance.api.js'
import { FinanceReceivableClaimApi } from '@/api/FinanceReceivableClaim.api.js'

export default {
  name: 'CreateModal',

  watch: {
  },

  computed: {
    setFormItem () {
      if (this.modalKey == 'lookModal') {
        this.formItem.map(item => {
          item.isDisabled = true
          if (['balanceAmt', 'dangqichae'].indexOf(item.model) != -1) {
            item.isShow = false
          }
        })
      } else {
        this.formItem.map(item => {
          if (['billAmt', 'balanceAmt', 'dangqichae', 'claimType', 'periodYM', 'insuranceTypes'].indexOf(item.model) != -1) {
            item.isDisabled = true
            if (['balanceAmt'].indexOf(item.model) != -1) {
              item.isShow = true
            }
          } else {
            item.isDisabled = false
          }
        })
      }
      return this.formItem
    }
  },

  data () {
    const validateAmt = (rule, value, callback) => {
      if (value == '' || value == null) {
        callback(new Error('请输入认领金额'))
      } else if (value <= 0) {
        callback(new Error('金额大于且不能等于0'))
      } else {
        callback()
      }
    }
    return {
      isShowCreateModal: false,
      // isCreate: true,
      modalKey: null,
      createModalTitle: null,
      isCanSubmit: true,
      parentFormData: null,
      formData: {
        id: null,
        companyID: null,
        companyName: null,
        periodYM: null,
        billAmt: null,
        balanceAmt: null,
        insuranceTypes: [],
        claimType: null,
        dangqichae: null,
        amt: null,
        remark: null,
      },
      formItem: [
        { type: 'select', label: '客户名称：', placeholder: '请选择客户名称', prop: 'companyID', model: 'companyID', style: 'ivu-col-span-12', options: 'customer', fn: 'companyIDChange', isShow: true },
        { type: 'select', label: '费用月份：', placeholder: '请选择费用月份', prop: 'periodYM', model: 'periodYM', style: 'ivu-col-span-12', mode: 'month', options: 'billMonths', fn: 'periodYMChange', isShow: true },
        { type: 'input', label: '账单金额：', placeholder: '请输入账单金额', prop: 'billAmt', model: 'billAmt', style: 'ivu-col-span-12', isDisabled: true, fn: 'billAmtChange', inputType: 'number', isShow: true },
        { type: 'input', label: '当期差额：', placeholder: '请输入当期差额', prop: 'balanceAmt', model: 'balanceAmt', style: 'ivu-col-span-12', fn: 'billAmtChange', inputType: 'number', isShow: true },
        { type: 'select', label: '到款所属项目：', placeholder: '到款所属项目', prop: 'insuranceTypes', model: 'insuranceTypes', style: 'ivu-col-span-12 is-required', options: 'financeclaimenum', fn: 'financeclaimenumChange', isShow: true },
        { type: 'input', label: '所属项目当期差额：', placeholder: '所属项目当期差额', prop: 'dangqichae', model: 'dangqichae', style: 'ivu-col-span-12', isDisabled: true, isShow: true },
        { type: 'select', label: '认领方式：', placeholder: '请选择认领方式', prop: 'claimType', model: 'claimType', style: 'ivu-col-span-12', options: 'claimTypeList', fn: 'claimTypeChange', isDisabled: true, isShow: true },
        { type: 'input', label: '认领金额：', placeholder: '请输入认领金额', prop: 'amt', model: 'amt', style: 'ivu-col-span-12', isShow: true },
        { type: 'input', label: '认领说明：', placeholder: '请输入认领说明', prop: 'remark', model: 'remark', style: 'ivu-col-span-12', isShow: true },
      ],
      rules: {
        companyID: [
          { required: true, message: '请选择客户名称', trigger: 'change' }
        ],
        periodYM: [
          { required: true, message: '请选择费用月份', trigger: 'change' }
        ],
        claimType: [
          { required: true, message: '请选择认领方式', trigger: 'change' }
        ],
        // insuranceTypes: [
        //   { required: true, message: '请选择到款所属项目', trigger: 'change' }
        // ],
        amt: [
          // { required: true, message: '请输入认领金额', trigger: 'change' },
          // { required: true, message: '金额大于且不能等于0', trigger: 'change', pattern: /(^\d+$)|(^\d+(\.\d+)?$)/ },
          { validator: validateAmt, trigger: 'change' }
        ]
      },
      arrListDown: {
        options: [],
        customer: [],
        billTypeList: [{ label: 'HRO', value: 'HRO' }],
        claimTypeList: [{ label: '全额认领', value: '1' }, { label: '差额认领', value: '2' }],
        statusList: [{ label: '正常', value: '1' }, { label: '回退', value: '0' }],
        billMonths: [],
        financeclaimenum: []
      },
      selectedMonth: null,
      selectedCompany: null,
      // selectedParentCompany: {}, // 选中的集团
    }
  },

  mounted () {
    this.enum()
    // this.getParentCompanys()
  },

  methods: {
    // 监听所有调用的方法
    listenCall (methodsWords, ...values) {
      this[methodsWords](...values)
    },
    
    // 获取公司
    // async companys () {
    //   var params = {
    //     PageIndex: 1,
    //     PageSize: 10000,
    //     Args: ''
    //   }
    //   Common.companys(params, this.arrListDown, 'customer')
    // },

    // 获取认领方式下拉框
    async enum () {
      let res = await FinanceReceivableClaimApi.enum()
      console.log('获取认领方式下拉框 res: ', res)
      if (res.status === 200) {
        res.data.map(item => {
          // this.arrListDown[item.group] = item.items
          if (item.group == 'financeclaimenum') {
            this.arrListDown.financeclaimenum = item.items
          }
        })
      } else {
      }
    },

    // 获取所属项目当期差额
    async getAmtByInsuranceType () {
      if (this.selectedMonth && this.selectedCompany && this.formData.insuranceTypes.length) {
        var params = {
          Year: this.selectedMonth.year,
          Month: this.selectedMonth.month,
          CompanyID: this.selectedCompany.value,
          InsuranceTypes: this.formData.insuranceTypes
        }
        let res = await FinanceReceivableClaimApi.getAmtByInsuranceType(params)
        console.log('获取所属项目当期差额 res: ', res)
        if (res.status === 200) {
          this.formData.dangqichae = res.data.data
          this.formData.amt = this.formData.dangqichae
        } else {
        }
      }
    },

    // 获取认领的公司下拉框-1
    async receivableCompanys (receiveID,matchRemark) {

      var params = {
        receiveID: receiveID,
        matchRemark: matchRemark
      }
      let res = await FinanceReceivableClaimApi.companys(params)
      console.log('获取认领的公司下拉框 res: ', res)
      if (res.status === 200) {
        var customerObj = res.data.find(item => {return item.group == 'customer'})
        var customerArr = []
        customerObj.items.map(item => {
          customerArr.push({value: item.key, label: item.value, yearMonths: item.yearMonths})
        })
        this.arrListDown.customer = customerArr
      } else {
        this.tableData = []
      }
    },

    // 客户名称改变-1
    async companyIDChange (model, value) {
      this.arrListDown.billMonths = []
      this.formData.periodYM = null
      this.formData.billAmt = null
      this.formData.balanceAmt = null

      if (value) {
        this.formItem.map(item => {
          if (item.model == 'periodYM') {
            item.isDisabled = false
          }
        })

        console.log('客户名称改变 model: ', model, ', value: ', value)
        this.selectedCompany = this.arrListDown.customer.find(item => {return value == item.value})
        console.log('选中的客户 this.selectedCompany: ', this.selectedCompany)

        this.arrListDown.billMonths = this.selectedCompany.yearMonths.map(item => {
          var month = item.month <= 9 ? '0' + item.month : item.month
          return {
            ...item,
            label: item.year + '-' + month,
            value: item.year + '-' + month
          }
        })
        console.log('this.arrListDown.billMonths: ', this.arrListDown.billMonths)

        this.getAmtByInsuranceType()
      }
      // this.formData.allBalanceTotal = this.selectedCompany.allBalanceTotal

      // // 带出来的金额跟父页面到款记录的金额不一致时 不允许全额认领
      // if (this.selectedCompany.allBalanceTotal !== this.parentFormData.amt) {
      //   this.formData.claimType = '2'
      //   this.formItem[2].isDisabled = true
      //   this.formData.amt = null
      //   this.formItem[3].isDisabled = false
      // }
    },

    // 费用月份改变-2
    periodYMChange (model, value) {
      // this.formData.periodYM = null
      this.formData.billAmt = null
      this.formData.balanceAmt = null
      this.formData.amt = null
      this.formData.dangqichae = null

      console.log('model: ', model, ', value: ', value)
      if (value) {
        this.formItem.map(item => {
          if (item.model == 'insuranceTypes') {
            item.isDisabled = false
          }
        })

        this.selectedMonth = this.arrListDown.billMonths.find(item => {return item.value == value})
        console.log('选择的月份及相关信息： ', this.selectedMonth)
        // this.formData.allBalanceTotal = this.selectedMonth.amt
        this.formData.year = this.selectedMonth.year
        this.formData.month = this.selectedMonth.month
        this.formData.balanceAmt = this.selectedMonth.balanceAmt
        this.formData.billAmt = this.selectedMonth.billAmt
        this.formData.amt = this.formData.claimType == 1 ? this.formData.balanceAmt : 0
        
        this.getAmtByInsuranceType()
      }
    },

    // // 数据字典-获取集团公司
    // getParentCompanys () {
    //   Common.getParentCompanys(this.arrListDown, 'parentCompanys')
    // },

    // // 数据字典-获取收款单位类型
    // getEnum () {
    //   let typeName = 'CollectionType'
    //   Common.getSelectIdList(typeName, this.arrListDown)
    // },

    cancel () {
      this.isShowCreateModal = false
    },

    show (parentFormData) {
      console.log('⭐ parentFormData: ', parentFormData)
      this.isCanSubmit = true
      this.isShowCreateModal = true
      this.$refs.formData.resetFields({})

      this.parentFormData = parentFormData
      this.selectedMonth = null
      this.selectedCompany = null
    },

    // 提交表单
    handleSubmit () {
      console.log('this.formData: ', this.formData)
      console.log('this.parentFormData: ', this.parentFormData)
      this.$refs.formData.validate((valid) => {
        if (valid) {
          this.isCanSubmit = false
          var selectedCompany = this.arrListDown.customer.find(item => {return item.value == this.formData.companyID})
          console.log('selectedCompany: ', selectedCompany)
          var params = {
            ReceiveID: this.parentFormData.receiveID,
            ClaimType: this.formData.claimType,
            CompanyID: selectedCompany.value,
            CompanyName: selectedCompany.label,
            Amt: this.formData.amt,
            Remark: this.formData.remark,
            DealTime: this.parentFormData.dealTime,
            BankName: this.parentFormData.bankName,
            Year: this.formData.year,
            Month: this.formData.month,
            BalanceAmt: this.formData.balanceAmt,
            BillAmt: this.formData.billAmt,
            InsuranceTypes: this.formData.insuranceTypes,
            // Amt: this.formData.dangqichae,
          }
          console.log('☆ params: ', params)
          FinanceReceivableClaimApi.addBillClaim(params).then(resp=>{
            if (resp.data.success) {
              this.$Message.success(resp.data.message)
              this.isShowCreateModal = false
              this.$emit('query')
            } else {
              this.isCanSubmit = true
              this.$Message.error(resp.data.message)
            }
          })
        } else {
          this.isCanSubmit = true
          this.$Message.warning('输入有误，请返回检查!')
        }
      })
    },

    // 根据ID获取信息
    async getModel (id) {
      let resp = await FinanceReceivableClaimApi.getInfo({id: id})
      if (resp.status === 200 && resp.data.success) {
        this.isShowCreateModal = true
        var result = resp.data.data
        // 相应赋值
        Object.keys(this.formData).forEach(key => {
          this.formData[key] = result[key] ? result[key] + '' : ''
        })

        this.formData.billAmt = result.billAmt
        this.formData.insuranceTypes = [result.insuranceType+'']

        // 费用月份-写死的
        var month = result.month <= 9 ? '0' + result.month : result.month
        this.formData.periodYM = result.year + '-' + month
        this.arrListDown.billMonths = [{label: result.year + '-' + month, value: result.year + '-' + month}]

        console.log('❤ this.formData: ', this.formData)
        // if (this.modalKey == 'lookModal') {
        //   this.setFormItem.map
        //   console.log('setFormItem: ', this.setFormItem)
        // }
      } else {
        this.$Message.error({
          content: resp.data.message,
          duration: 10,
          closable: true
        })
      }
    },

    // 认领方式改变
    claimTypeChange (model, value) {
      console.log('认领方式改变 model: ', model, ', value: ', value)
      if (this.modalKey !== 'lookModal' && value) {
        this.formItem.map(item => {
          if (item.model == 'amt') {
            item.isDisabled = value == 1 ? true : false
            this.formData.amt = value == 1 ? this.formData.dangqichae : 0
          }
        })
      }
    },

    // 时间选择改变
    datePickerChange (model, value) {
      console.log('model: ', model, ', value: ', value)
      this.formData[model] = value
    },

    // 账单金额改变
    billAmtChange (model, event) {
      console.log('model: ', model, ', event: ', event.target.value)
      this.formData.amt = this.formData.claimType == 1 ? this.formData.balanceAmt : 0
    },

    // 到款所属项目改变
    financeclaimenumChange (model, event) {
      // if (event.length) {
      //   this.formItem.map(item => {
      //     if (item.model == 'claimType') {
      //       item.isDisabled = false
      //     }
      //   })
      // } else {
      //   this.formItem.map(item => {
      //     if (item.model == 'claimType') {
      //       item.isDisabled = true
      //     }
      //   })
      // }

      console.log('到款所属项目改变 model: ', model, ', event: ', event)
      if (this.modalKey !== 'lookModal') {
        this.formData.insuranceTypes = event
        this.getAmtByInsuranceType()

        if (event.length > 1) {
          // 到款所属项目多选时，认领方式为全额认领
          this.formData.claimType = '1'
          this.formItem.map(item => {
            if (['claimType', 'amt'].indexOf(item.model) != -1) {
              item.isDisabled = true
            }
          })
          // setTimeout(() => {
            
          // }, timeout);
          // this.formData.amt = this.formData.dangqichae
        } else {
          this.formData.claimType = null
          this.formItem.map(item => {
            if (['claimType','amt'].indexOf(item.model) != -1) {
              item.isDisabled = false
            }
          })
          this.formData.amt = null

          if (event.length == 0) {
            this.formData.dangqichae = null
          }
        }
      }
    },
  }
}
</script>

<style lang="less" scoped>

</style>
